package dao.sql;

import dao.FolderDAO;
import domain.Folder;
import facade.ShopException;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class HsqldbFolderDAO implements FolderDAO {

    Statement sqlStatement;

    public HsqldbFolderDAO(Connection connection) throws Exception {
        try {
            sqlStatement = connection.createStatement();
        } catch (SQLException ex) {
            throw new ShopException(ex);
        }
    }


    public void createFolder(String folderName, String description, Integer parentId) throws Exception {
        int n = sqlStatement.executeUpdate("insert into FOLDERS values(null, '" + folderName + "','" + description + "','" + parentId + "')");
    }

    public void save(Folder folder) throws Exception {
        if (folder.getId() == null) {
            Integer id = folder.getParentId();
            if (id == null) {
                id = 0;
            }
            int n = sqlStatement.executeUpdate("insert into FOLDERS values(null, '" + folder.getFolderName() + "','" + folder.getDescription() + "','" + id.toString() + "')");
        } else {
            int n = sqlStatement.executeUpdate("update \"FOLDERS\" " + "" +
                    "set \"FOLDER_NAME\" = '" + folder.getFolderName() + "' ," +
                    "\"DESCRIPTION\" = '" + folder.getDescription() + "'" +
                    "\"PARENT_ID\" = '" + folder.getParentId() + "'" +
                    "where \"ID\" = " + folder.getId());
            if (n != 1) {
                throw new ShopException("Update failed");
            }
        }
    }

    public Folder findById(Integer folderId) throws Exception {
        ResultSet resultSet;
        resultSet = sqlStatement.executeQuery("select * from \"FOLDERS\" where \"ID\" = " + folderId);
        if (resultSet.next()) {
            Folder folder = new Folder(resultSet.getInt("ID"), resultSet.getString("FOLDER_NAME"));
            folder.setParentId(resultSet.getInt("PARENT_ID"));
            folder.setDescription(resultSet.getString("DESCRIPTION"));
            return folder;
        }
        return null;
    }

    public Collection<Folder> findAll() throws Exception {
        List<Folder> allReaders = new ArrayList<Folder>();
        ResultSet resultSet = sqlStatement.executeQuery("select * from \"FOLDERS\"");
        while (resultSet.next()) {
            Folder reader = new Folder(resultSet.getInt("ID"), resultSet.getString("FOLDER_NAME"));
            allReaders.add(reader);
        }
        return allReaders;
    }

    public void delete(Integer folderId) throws Exception {
        sqlStatement.executeUpdate("delete from \"FOLDERS\" where \"ID\" = " + folderId);
    }


    public void close() throws Exception {
        sqlStatement.close();
    }
}